;(function($) {
    $.extend({
        //获取浏览器类型
        getBrowserMsg:function(){
            var Sys = {};
            var ua = navigator.userAgent.toLowerCase();
            var s;
            (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
                (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                    (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                            (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
            return Sys;
        },
        /**
         * 序列化表单
         * @param form 表单对象
         * @param returnString 返回的数据类型，默认是json对象,为true时返回的是一个json字符串
         */
        serializeForm:function(form,returnString){//根据表单对象获取表单数据 ,返回类型为json对象
            var serializeObj = {};
            if(!(form instanceof jQuery)){
                form = $(form);
            }
            var array = form.serializeArray();
            $(array).each(function(){
                if(serializeObj[this.name]){
                    if($.isArray(serializeObj[this.name])){
                        serializeObj[this.name].push(this.value);
                    }else{
                        serializeObj[this.name]=[serializeObj[this.name],this.value];
                    }
                }else{
                    serializeObj[this.name]=this.value;
                }
            });
            //返回json字符串
            if(returnString){
                return JSON.stringify(serializeObj);
            }
            return serializeObj;
        },
        //判断字符串不为空
        isNotEmpty:function(chkStr) {
            if (chkStr == null) return false;
            if (typeof (chkStr) == 'undefined') return false;
            if (typeof (chkStr) == 'String') chkStr = chkStr.trim();
            if (chkStr == "" || chkStr == "null" || chkStr == "&nbsp;") return false;
            return true;
        },
        //显示layer弹出框
        layer_show:function(opt){
            opt.content = opt.content.indexOf("?") > 0 ? opt.content + "&baseUri=%2Findex.html" : opt.content + "?baseUri=%2Findex.html";
            opt.content = sys.rootPath + "/" +opt.content;
            if ($.isNotEmpty(opt.content) && opt.type == 2)
                opt.content = sys.rootPath + content;
            if (!$.isNotEmpty(opt.content) && opt.type == 2)
                opt.content = sys.rootPath + "error/error-404.jsp";
            this.defaults = {
                type : 2, //iframe
                area : ['750px', '600px'], //弹出框大小
                shift : 1, //是否显示动画效果 0-6， -1表示不显示动画效果
                shade: 0.6, //遮罩透明度
                maxmin : true, //是否允许最大化
                fix: false, //是否不固定
                zIndex: layer.zIndex,
                success: function(layero){
                    layer.setTop(layero);
                }
            },
            this.options = $.extend({}, this.defaults, opt)
            var _layer = layer.open(this.options);
            if(opt.full)
                layer.full(_layer);
            return _layer;
        },
        //显示选择带回的layer弹出框
        layer_bringBack:function(opt){
            if ($.isNotEmpty(opt.content) && opt.type == 2)
                opt.content = sys.rootPath + content;
            if (!$.isNotEmpty(opt.content) && opt.type == 2)
                opt.content = sys.rootPath + "error/error-404.jsp";
            var currentIndex;
            this.defaults = {
                type : 2, //iframe
                area : ['750px', '600px'], //弹出框大小
                shift : 1, //是否显示动画效果 0-6， -1表示不显示动画效果
                shade: 0.6, //遮罩透明度
                maxmin : true, //是否允许最大化
                fix: false, //是否不固定
                zIndex: parent.layer.zIndex,
                success: function(layero){
                    parent.layer.setTop(layero);
                }
                ,btn: ['确定', '取消']
                ,yes: function(){
                    var parentIndex = parent.layer.getFrameIndex(window.name);
                    var frameName = "layui-layer-iframe" + currentIndex; //获得layer层的iframe名字
                    var gridObjStr = opt.grid;
                    var record;
                    try {
                        record = parent.frames[frameName].eval(gridObjStr).getCheckedRecords();
                    } catch (e) {
                        record = parent.frames[frameName].eval(gridObjStr).bootstrapTable('getSelections');
                    }
                    /*if (opt.multi == true && record.length <= 0) {
                        top.layer.msg("你还没有选择行"); return;
                    } else if(opt.multi == false && record.length != 1) {
                        top.layer.msg("你没有选择行或选择了多行数据"); return;
                    }*/
                    parent.layer.close(currentIndex);
                    if (typeof opt.callback === 'function') {
                        opt.callback(record);
                    }
                }
            },
            this.options = $.extend({}, this.defaults, opt)
            var _layer = parent.layer.open(this.options);
            parent.layer.full(_layer);
            currentIndex = _layer;
            return _layer;
        },
        //关闭弹出框口
        layer_close:function(){
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },
        layer_confirm:function() {
            layer.confirm('您是如何看待前端开发？', {
                btn: ['重要', '奇葩'] //按钮
            }, function () {
                layer.msg('的确很重要', {icon: 1});
            }, function () {
                layer.msg('也可以这样', {
                    time: 20000, //20s后自动关闭
                    btn: ['明白了', '知道了']
                });
            })
        }
    });
})(jQuery);


/**
 * 自定义表单验证提示效果，让提示信息滑入显示,
 * 依赖于Validform5+以上版本
 * Validform API:http://validform.rjboy.cn/document.html
 * */
(function($){
    /**
     * @param config 使用跟Validform的配置即可
     * @param args 为false时，该功能不起作用
     * */
    $.fn.customValidform = function(options,args){
        //tiptype可用的值有：1、2、3、4和function函数，默认tiptype为1。 3、4是5.2.1版本新增
        options = options || {tiptype:2};
        var result = {};
        var _this = $(this);
        if(args != false){
            options['tiptype'] = function(msg,o,cssctl){
                //msg：提示信息;
                //o:{obj:*,type:*,curform:*}, obj指向的是当前验证的表单元素（或表单对象），type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
                //cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
                //var isPass = true;//是否验证通过
                if(!o.obj.is("form")){//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
                    var objtip = o.obj.parent().find(".Validform_checktip");
                    if(objtip.length == 0){
                        var html = '<div class="Validform_info">'
                            +'<span class="Validform_checktip Validform_wrong" style="margin-left:0;">'+msg+'</span>'
                            +'<span class="Validform_dec">'
                            +'<s class="dec1">◆</s>'
                            +'<s class="dec2">◆</s>'
                            +'</span>'
                            +'</div>';
                        o.obj.parent().append(html);
                        objtip = o.obj.parent().find(".Validform_checktip");
                    }else{
                        objtip.html(msg);
                    }
                    cssctl(objtip,o.type);
                    var infoObj = o.obj.parent().find(".Validform_info");
                    if(o.type==2){
                        infoObj.fadeOut(200);
                    }else{
                        //isPass = false;
                        if(infoObj.is(":visible")){return;}
                        //var left=o.obj.offset().left;
                        //top=o.obj.offset().top;
                        var top = o.obj.outerHeight(),
                            left = o.obj.outerWidth();
                        var browserV = $.getBrowserMsg();
                        if(browserV.ie != undefined && parseFloat(browserV.ie) > 8){
                            top = o.obj.height();
                        }
                        infoObj.css({
                            left:left/2,
                            top:-top
                        }).show().animate({
                            //top:top-5
                        },200);
                    }
                    //options['isPass'] = isPass;
                }
            };
        }
        result = _this.Validform(options);
        return result;
    };
})(jQuery);

/*-----------------------------表单提交插件begin----------------------------------*/
/*依赖layout做弹出提示*/
(function(){
    $.fn.ajaxSubmitForm = function(options){
        var $this = this;
        if(!($this instanceof jQuery)){$this = $($this);}
        if($this.attr('action')) options['url'] = $this.attr('action');
        options = $.extend({},$.fn.ajaxSubmitForm.defaults,
            typeof options === 'object' && options);
        if(options.url){
            options.url = sys.rootPath + options.url;
            var formData;
            //默认提交参数类型为json对象
            formData = $.extend({},$.serializeForm($this),options.params);
            //提交参数类型为json字符串
            if(options.paramField){//自己指定提交参数字段{paramField:json字符串}
                //后台接收到的参数是 String
                var newData = formData;
                formData = {};
                formData[options.paramField] = newData;
            }else if(options.paramType.toUpperCase() == 'STRING'){//直接提交一个json字符串
                //后台使用@RequestBody Entity将该JSON字符串转成对应的对象
                formData = JSON.stringify(formData);
                options.contentType = 'application/json';
            }

            if(options.confirm){
                layer.open({
                    content: options.confirmMsg,
                    btn: options.btn,
                    shadeClose: false,
                    title:options.title,
                    zIndex: layer.zIndex,
                    success: function(layero){
                        layer.setTop(layero);
                    },
                    icon:3,
                    tipsMore:true,
                    yes: function(index, layero){
                        top.layer.close(index);
                        submitServer(options,formData);
                    },cancel: function(index){
                        layer.close(index);
                        options.onCancel.call(this,index);
                    }
                });
            }else{
                submitServer(options,formData);
            }

        }else{
            layer.alert('URL 无效', {icon: 5});
        }
    };
    //提交请求
    function submitServer(options,formData){
        var tipMsg = layer.msg(options.waitMsg, {icon: 16,shade:[0.1,'#000'],time:0});
        options.onBeforeSubmit.call(this,formData);
        $.ajax({
            url:options.url,
            type:options.method,
            data: formData,
            dataType:'json',
            contentType:options.contentType,
            success: function(jsonLst) {
                options.onSubmitSuccess.call(this,jsonLst);
                layer.close(tipMsg);
            },
            error: function(xhr, textStatus, errorThrown){
                options.onSubmitError.call(this,xhr, textStatus, errorThrown);
                layer.close(tipMsg);
            }
        });
    }
    //默认配额制项
    $.fn.ajaxSubmitForm.defaults = {
        url:'',
        method:'post',
        paramType:'object',//提交的参数类型，默认是json对象，如果是string，则提交的数据是json字符串
        paramField:'',//提交数据为json字符串时，提交到后台的参数名
        confirm:true,//提交前是否弹出提示，默认是
        confirmMsg:'确定提交保存？',
        waitMsg:'正在保存，请稍等...',
        btn: ['确认', '取消'],
        title:'提示',
        zIndex:19891231,
        contentType:'application/x-www-form-urlencoded;charset=utf-8',
        params:{},//要添加到表单一起提交的参数
        onBeforeSubmit:function(data){},//表单数据
        onSubmitSuccess:function(ret){},//ret是提交成功后的返回值
        onSubmitError:function(xhr, textStatus, errorThrown){},
        onCancel:function(index){}//取消保存操作
    };
})(jQuery);
/*-----------------------------表单提交插件end------------------------------------*/

//绑定字典内容到指定的Select控件
function BindSelect(ctrlName, url, selectedVal) {
    var control = $('#' + ctrlName);
    //设置Select2的处理
/*    control.select2({
        allowClear: true,
        placeholder: '请选择',
        formatResult: function(repo){return repo.text}, //返回结果回调
        formatSelection: function(repo){return repo.text}, //选中项回调
        escapeMarkup: function (m) { //字符转义处理
            return m;
        }
    });*/
    var result;
    //绑定Ajax的内容
    $.getJSON(url, function (data) {
        result = data;
        control.empty();//清空下拉框
        control.append("<option value>--请选择--</option>");
        $.each(data, function (i, item) {
            if ($.isNotEmpty(selectedVal) && item.dictValue == selectedVal) {
                control.append("<option selected='selected' value='" + item.dictValue + "'>" + item.dictName + "</option>");
            } else {
                control.append("<option value='" + item.dictValue + "'>" + item.dictName + "</option>");
            }
        });
    });
    return result;
}

//为Select控件绑定内容
function BindSelect2(id, data, url, selectedVal, multiple) {
    var control = $('#' + id);
    control.select2({
        // placeholder:'--请选择--',
        // allowClear:true,
        multiple: multiple
    });
    if (!$.isNotEmpty(url) && $.isNotEmpty(data)) {
        control.empty();//清空下拉框
        $.each(data, function(i) {
            if ($.isNotEmpty(selectedVal) && i == selectedVal) {
                control.append("<option selected='selected' value='" + i + "'>" + data[i] + "</option>");
            } else {
                control.append("<option value='" + i + "'>" + data[i] + "</option>");
            }
        });
    } else {
        $.getJSON(url, function (data) {
            result = data;
            control.empty();//清空下拉框
            $.each(data, function (i, item) {
                if ($.isNotEmpty(selectedVal) && item.dictValue == selectedVal) {
                    control.append("<option selected='selected' value='" + item.dictValue + "'>" + item.dictName + "</option>");
                } else {
                    control.append("<option value='" + item.dictValue + "'>" + item.dictName + "</option>");
                }
            });
        });
    }
}

/**
 * 选择带回功能组件
 * @param title
 * @param url 要请求的url
 * @param gridObj 弹出页面中的list对象名称
 * @param callbackFun 回调函数
 */
function chooseToBringBack(title, url, gridObj, multi, callbackFun) {
    var multi = multi == undefined || multi == '' ? false : multi;
    var record = top.$.layer_bringBack({title: title, content: sys.rootPath + url, grid: gridObj, multi: multi, callback: callbackFun});
}

/**
 * 让时间呈现的形式为：N分钟前（小时，天，年）
 * @type {number[]}
 */
var byTime = [365*24*60*60*1000, 30*24*60*60*1000, 7*24*60*60*1000, 24*60*60*1000, 60*60*1000, 60*1000, 1000];
var unit = ["年", "月", "周", "天", "小时", "分钟", "秒钟"];
function getDateDiff(dateStr){
    var ct = new Date().getTime()-Date.parse(dateStr.replace(/-/gi,"/"));
    if(ct<0){
        return "";  //当前时间 < 输入的时间
    }
    var sb = [];
    for(var i=0;i<byTime.length;i++){
        if(ct<byTime[i]){
            continue;
        }
        var temp = Math.floor(ct/byTime[i]);
        ct = ct%byTime[i];
        if(temp>0){
            sb.push(temp+unit[i]);
        }
        if(sb.length>=1){
            break;
        }
    }
    return sb.join("")+"前";
}

/**
 *
 * @param dictObj 对应字典的json对象
 * @param id  组件ID
 * @param extentContent 除字典信息外的附加选项添加
 */
function appendHtmlForSelect(dictObj, id, extentContent, selectedVal) {
    var selOption = extentContent == undefined || extentContent == "" ? "<option value=''></option>" : extentContent;
    $.each(dictObj, function(i) {
        if ($.isNotEmpty(selectedVal) && i == selectedVal) {
            selOption += "<option selected='selected' value='" + i + "'>" + dictObj[i] + "</option>";
        } else {
            selOption += "<option value='" + i + "'>" + dictObj[i] + "</option>";
        }
    });
    $('#'+id).append(selOption);
}

/**
 * 获取当前活动的iframe
 * @param String childIframeName 子iframe
 */
function getParentIframe(childIframeName) {
    var menuArr = $(parent.document).find('.J_menuTab');
    var index = 0;
    $.each(menuArr, function (i) {
        if ($(this).hasClass('active') == true) {
            index = i;
        }
    });
    var iframeName = $($(parent.document).find(".J_iframe")[index]).attr('name');
    if ($.isNotEmpty(childIframeName))
        return parent.frames[iframeName].frames[childIframeName];
    return parent.frames[iframeName];
}

/**
 * 根据子iframe（二级）名称获取iframe
 * @param name
 * @returns {*}
 */
function getIframeByName(name) {
    var menuArr = $(parent.document).find('.J_menuTab');
    var iframe;
    $.each(menuArr, function (i) {
        var iframeName = $($(parent.document).find(".J_iframe")[i]).attr('name');
        iframe = parent.frames[iframeName].frames[name];
        if($.isNotEmpty(iframe)) {
            return false;
        }
    });
    return iframe;
}
